package com.le.tester.book.concurrentchallenge.effScalingCache;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * createTime：2025-03-27 10:11
 * description：使用ConcurrentHashMap,使得get，和put 是线程安全
 */
public class Memoizerl2<A, V> implements Computable<A, V> {

    private final Map<A, V> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    public Memoizerl2(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws InterruptedException {
        V result = cache.get(arg);

        if (result == null) {
            result = c.compute(arg);
            cache.put(arg, result);
        }
        return result;
    }
}
